package com.bestcem.xm.member.dao.impl.mysql;

import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.uitls.StringUtil;
import com.bestcem.xm.member.dao.DisplayRangeDao;
import com.bestcem.xm.member.dao.mapper.DisplayRangeMapper;
import com.bestcem.xm.member.entity.mongo.DisplayRange;
import com.bestcem.xm.member.entity.mysql.DisplayRangeEntity;
import com.bestcem.xm.member.entity.pojo.DisplayRangeDO;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.annotation.Nullable;
import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

/**
 * @author dc.wang <dc.wang@idiaoyan.com>
 * @version V1.0
 * @description
 * @date 2021/7/7
 */
@Repository
public class DisplayRangeDaoImpl implements DisplayRangeDao {
    @Resource
    private DisplayRangeMapper displayRangeMapper;

    @Nullable
    @Override
    public DisplayRangeDO findByOrgAndMemberType(@NotNull String orgId, @NotNull Integer memberType) {
        DisplayRangeEntity entity = displayRangeMapper.findOneByOrgIdAndMemberType(orgId, memberType);
        return DisplayRangeDO.toDo(entity);
    }

    @Override
    public @NotNull DisplayRangeDO create(DisplayRangeDO displayRangeDo) {
        displayRangeDo.setDisplayId(StringUtil.getId());
        displayRangeMapper.createDisplayRange(DisplayRangeDO.toEntity(displayRangeDo));
        DisplayRangeEntity entity = displayRangeMapper.findById(displayRangeDo.getDisplayId());
        return DisplayRangeDO.toDo(entity);
    }

    @Override
    public @NotNull DisplayRangeDO update(DisplayRangeDO displayRangeDo) {
        displayRangeMapper.updateById(DisplayRangeDO.toEntity(displayRangeDo));
        DisplayRangeEntity entity = displayRangeMapper.findById(displayRangeDo.getDisplayId());
        return DisplayRangeDO.toDo(entity);
    }

    private DisplayRangeEntity convert(DisplayRange displayRange){
        DisplayRangeEntity entity = new DisplayRangeEntity();
        entity.setDisplayId(displayRange.getId());
        entity.setOrgId(displayRange.getOrgId());
        entity.setMemberType(displayRange.getMemberType());
        entity.setType(displayRange.getType());
        if(!CollectionUtils.isEmpty(displayRange.getRoleIds())){
            entity.setRoleIds(JSONObject.toJSONString(displayRange.getRoleIds()));
        }
        entity.setCreateTime(displayRange.getCreateTime());
        entity.setUpdateTime(displayRange.getUpdateTime());
        return entity;
    }
}
